import json

from client.redis_client import r
from dao.es_dao.compare_data_dao import save_single_compare_location, save_single_compare_step, \
    save_single_compare_health
from utils.date_utils import DateTimeCombiner, timestamp_to_date
from utils.logger_util import logger


async def save_compare_location(data):
    # 距离15分钟时间窗口大于1分钟，则记入校正对齐队列，在下一次15分钟窗口进行定位集中定位
    compare_result = DateTimeCombiner.is_time_diff_over_second(timestamp_to_date(data['timestamp']), 60)
    if compare_result['is_near']:
        source = json.loads(r.hget('state_' + data["device_id"], 'source'))
        if source is not None:
            await save_single_compare_location(data, source['departId'], compare_result['is_floor'])
    else:
        r.hset('diff_15', data['device_id'], 1)


async def save_compare_health(data):
    # 距离30分钟时间窗口大于2分钟，则记入校正对齐队列，在下一次15分钟窗口进行定位集中定位
    compare_result = DateTimeCombiner.is_time_diff_over_second(timestamp_to_date(data['timestamp']), 120,
                                                               window_time=30)
    if compare_result['is_near']:
        source = json.loads(r.hget('state_' + data["device_id"], 'source'))
        if source is not None:
            await save_single_compare_health(data, source['departId'], compare_result['is_floor'])
    else:
        r.hset('diff_30', data['device_id'], 1)


async def save_compare_step(data):
    try:
        source = json.loads(r.hget('state_' + data["device_id"], 'source'))
        if source is not None:
            await save_single_compare_step(data, source['departId'])
    except Exception as e:
        logger.error(e)